<template>
  <el-dialog :title="dialogTitle" :visible.sync="showDialog_" top="0%" custom-class='dialog_right dialogScroll_add MkAddDoctor' @open="openDialog" @close="closeDialog('addForm')">
    <el-scrollbar :wrapStyle="[{maxHeight:(bodyHeight-200)+'px'}]">
      <el-form :model="addForm.formItem" :rules="addForm.rules" ref="addForm" label-width="110px">
        <el-form-item label="姓名" prop="name">
          <el-input v-model='addForm.formItem.name' placeholder="请输入姓名（必填）">
          </el-input>
        </el-form-item>
        <el-form-item label="电话号码" prop="phone">
          <el-input v-model='addForm.formItem.phone' placeholder="请输入电话号码（必填）" :maxlength="11">
          </el-input>
        </el-form-item>
        <el-form-item label="科室" prop='departmentId'>
          <el-select  placeholder="请选择科室（必选）" v-model='addForm.formItem.departmentId'>
            <el-option v-for="item in departments" :label="item.name" :value="item.id" :key="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="职称" prop='titleOfDoctorId'>
          <el-select  placeholder="请选择职称（必选）" v-model='addForm.formItem.titleOfDoctorId'>
            <el-option v-for="item in titles" :label="item.name" :value="item.id" :key="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="就职医院" prop="inauguralHospital">
          <el-input v-model='addForm.formItem.inauguralHospital' placeholder="请输入就职医院（必填）">
          </el-input>
        </el-form-item>
        <el-form-item label="所在城市" prop="cityId">
          <el-cascader
          :props="options"
          :options="siteArr"
          v-model="siteSelect"
          placeholder="请所在城市（必选）"
          @change="handleChange">
        </el-cascader>
        </el-form-item>
        <el-form-item label="擅长领域" >
          <el-tag
            :key="tag.value"
            v-for="tag in tags"
            :closable="true"
            type='primary'
            :close-transition="false"
            @close="handleClose(tag)"
          >
            {{tag}}
              </el-tag>
          <el-input
            class="input-new-tag"
            v-if="inputVisible"
            v-model="inputValue"
            ref="saveTagInput"
            placeholder='请输入选项内容，回车保存'
            size=""
            :maxlength='8'
            @keyup.enter.native="handleInputConfirm"
            @blur="handleInputConfirm"
          >
          </el-input>
          <el-button v-else type="text" class="button-new-tag"  @click="showInput" :maxlength="8">+ 添加选项</el-button>
        </el-form-item>
        <el-form-item label="个人简介"  prop='content'>
          <el-input v-model="addForm.formItem.content" placeholder='请输入个人简介' size=""
                    type='textarea' :rows='3' resize='none' :maxlength="500"></el-input>
        </el-form-item>
        <el-form-item label="头像"  prop='avatarId'>
          <el-upload
            accept=".jpeg, .jpg, .png, .gif"
            class="avatar-uploader" :action="'/upload/image.json'"
            :show-file-list="false"
            :data="{'width':400,'height':400}"
            :on-success="handleSuccess"
            :before-upload="beforeAvatarUpload"
            name="image">
            <img v-if="dialogImageUrl" :src="dialogImageUrl" class="avatar" >
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
          <p style="color:#83a0a5;font-size:14px;">建议上传400*400规格的图片</p>
        </el-form-item>
      </el-form>
    </el-scrollbar>

    <div slot="footer" class="dialog-footer">
      <el-button type="primary" class="btn-primary" @click="submitForm('addForm')" v-loading.fullscreen.lock="fullscreenLoading">提交</el-button>
      <el-button type='primary' class="btn-cancel" @click="showDialog_=false">取消</el-button>
    </div>
  </el-dialog>
</template>

<script>
  import doctorService from '../../services/doctor'
  import {mapState} from 'vuex'
  export default {
    name: 'MkAddDoctor',
    props: ['showDialog','currentCustomer'],
    computed:mapState({
      bodyHeight: state => state.global.bodyHeight,
    }),
    watch: {
      showDialog: function(value) {
        this.showDialog_ = value;
      },
    },
    methods: {
      changeField(form, formName, field) {
        this[form].formItem[field] = this[form].formItem[field].trim();
        this.$refs[formName].validateField(field);
      },
      loadCities() {
        doctorService.loadCitiesListAdd(data=>{
          this.siteArr = data.data;
        })
      },
      handleChange() {
        this.beforeSelect =  false;
        this.addForm.formItem.cityId = this.siteSelect[1];
      },
      loadDepartments() {
        doctorService.loadDoctorDepartmentList(data=>{
          this.departments = data.data;
        })
      },
      loadTitles() {
        doctorService.loadDoctorTitleList(data=>{
          this.titles = data.data;
        })
      },
      openDialog() {
        this.isRefresh = false;
        this.clickSubmitBtn = false;
        this.loadCities();
        this.loadDepartments();
        this.loadTitles();
        let currentCustomer = this.currentCustomer;
        let form  = this.addForm.formItem;
        if(currentCustomer) {
          this.dialogTitle = '编辑名医';
          this.tags=this.currentCustomer.goodField?this.currentCustomer.goodField.split(","):[];
          form.avatarId = currentCustomer.avatarId;
          form.cityId = currentCustomer.cityId;
          form.content = currentCustomer.content;
          form.departmentId = currentCustomer.departmentId;
          form.id = currentCustomer.id;
          form.inauguralHospital = currentCustomer.inauguralHospital;
          form.name = currentCustomer.name;
          form.phone = currentCustomer.phone;
          form.titleOfDoctorId = currentCustomer.titleOfDoctorId;
          this.dialogImageUrl= currentCustomer.avatar;
          this.siteSelect[0]=currentCustomer.provinceId;
          this.siteSelect[1]=currentCustomer.cityId;
          this.siteSelect[2]=currentCustomer.areaId;
        }
      },
      closeDialog(formName) {
        this.$refs[formName].resetFields();
        let form = this.addForm.formItem;
        for(let i in form) {
          form[i] = '';
        }
        this.tags.splice(0,this.tags.length);
        this.dialogImageUrl='';
        //        this.addForm.formItem.goodField='';
//        this.addForm.formItem.avatarId='';
        this.siteSelect.splice(0,this.siteSelect.length);
        this.$emit('closeDialog',this.isRefresh);
      },
      submitForm(formName) {
        this.$refs[formName].validate(valid=>{
          if(valid) {
            this.addForm.formItem.goodField=this.tags.join(",");
            if (!this.clickSubmitBtn) {
              this.fullscreenLoading = true;
              this.clickSubmitBtn = true;
              doctorService.loadDoctorEdit(this.addForm.formItem,data=>{
                this.$message.success('保存成功');
                this.isRefresh = true;
                this.showDialog_ = false;
                this.fullscreenLoading = false;
              },data=>{
                this.fullscreenLoading = false;
                this.clickSubmitBtn = false;
              })
            }
          }
        })
      },
      beforeAvatarUpload(file) {
      },
      handleSuccess(res, file) {
        this.dialogImageUrl = URL.createObjectURL(file.raw);
        this.addForm.formItem.avatarId = res.data.fileId;
        this.$refs['addForm'].validateField('avatarId');
      },
      showInput() {
        if(this.tags.length>9){
          this.$message.warning('最多添加10个');
          return false;
        }
        this.inputVisible = true;
        this.$nextTick(_ => {
          this.$refs.saveTagInput.$refs.input.focus();
        });
      },
      handleInputConfirm() {
        let inputValue = this.inputValue;
        if (inputValue) {
          var obj=this.tags;
          for(var i=0;i<obj.length;i++) {
            if(obj[i]==inputValue){
              this.$message.success( '已存在');
              return;
            }
          }
          this.tags.push(inputValue);
        }
        this.inputVisible = false;
        this.inputValue = '';
      },
      handleClose(tag) {
        this.tags.splice(this.tags.indexOf(tag), 1);
      },
    },
    data() {
      let checkPhone = (rule, value, callback) => {
        if (value) {
          let reg = new RegExp("^1(3|4|7|5|8)([0-9]{9})");
          if (!reg.test(value)) {
            callback(new Error('请输入正确格式的手机号'));
          } else {
            callback();
          }
        } else {
          callback(new Error('请输入联系电话'));
        }
      };
      return {
      timer: false,
        searchSiteCondition:{
          id: '',
          proId: ''
        },
//        isFirst: true,
        clickSubmitBtn: false,
        fullscreenLoading: false,
        departments:'',
        titles:'',
        isRefresh: false,
        fileList:[],
        showDialog_: this.showDialog,
        dialogTitle: '新增名医',
        addForm: {
          formItem: {
//            areaId: '',
            avatarId: '',
            cityId: '',
            content: '',
            departmentId: '',
            goodField: '',
            id: '',
            inauguralHospital: '',
            name: '',
            phone: '',
            titleOfDoctorId: '',
          },
          rules: {
            phone:{ validator: checkPhone, trigger: 'change' },
            name:{required:true,message:'请输入姓名',trigger:'change'},
            departmentId:{required:true,message:'请选择科室',trigger:'change',type:'number'},
            titleOfDoctorId:{required:true,message:'请选择职称',trigger:'change',type:'number'},
            inauguralHospital:{required:true,message:'请输入就职医院',trigger:'change'},
            cityId:{required:true,message:'请选择所在城市',trigger:'change',type:'number'},
          }
        },
        dialogImageUrl:'',
        siteArr: [],
        siteSelect: [],
        options: {
          value: 'id',
          label:'name',
          children: 'city'
        },
        inputVisible: false,
        inputValue: '',
        tags:[],
      }
    }
  }

</script>

<style lang="less">
  @import '../../assets/style/main.less';
  .MkAddDoctor {
    .el-tag {
      margin-right: 10px;
      margin-bottom:10px;
      background:rgba(59,192,195,0.2);
      border:1px solid rgba(59,192,195,0.1);
    }
    .el-button--mini.button-new-tag{
      border: 1px solid lightgrey;
      &:hover{
        border: 1px solid @primaryColor;
      }
    }
  }
</style>
